// Page
const app = getApp(

)
var utils = {
  digit: function (n) {
    if (n == null || n === "" || n == undefined) {
      return "";
    } else {
      n = n.toString();
      return n[1] ? n : '0' + n;
    }
  },
  formatDate: function (date = new Date()) {
    // 年月日
    var year = date.getFullYear()
    var month = date.getMonth() + 1
    var day = date.getDate()
    // 返回值
    return [year, this.digit(month)].map(this.digit).join('-');
  }
}


Page({
  data: {
    // 左右滑动的class样式
    slideOne: "",
    slideTwo: "",
    // 左右滑动定义的状态变量
    slideFlag: false,

    // 页面输出的数据
    currentDate: utils.formatDate(),
    weeks: ['日', '一', '二', '三', '四', '五', '六'],
    inputUp: true,
    bmi: 0.0,
    fate_rate: 0.0,
    height: 0,
    weight: 0.0,
    target: 0.0,
    renwu_url: '//resource.160nurse.com/canvas/healthy/img/bmi/female_bz.png',
    curDate: '',
    currentValue: '',
    currentWeight: '',
    total_num: 0,
    fat_rate: 0,
    inputFocus: false,
    inputFocus2: false,
    openGuize: false,
    page: 1,
    size: 10,
    chapter: [],
    isBottom: false
  },

  onLoad: function (options) {
    let sex = ''
    let id = ''
    let type = ''
    let news = ''
    if (options && options.id) {
      id = options.id
    }
    if (options && options.type) {
      type = options.type
    }
    if (options && options.sex) {
      sex = options.sex
    }
    if (options && options.news) {
      news = options.news
    }
    this.setData({
      id,
      type,
      sex,
      news
    })
    console.log(type)
    this.getUnit()
    this.generateDaily()
    this.getWidth()
    this.drawCanvasbg()
    this.getBMI()
    this.getChapter()
    // this.drawProgress(1)
  },
  getHeight (e) {
   let that = this
   console.log(e.detail)
   that.setData({
     bottom: e.detail
   })
  },
  getUnit() {
    let that = this
    wx.getSystemInfo({
      success: function(res) {
        let unit = res.screenWidth / 100
        that.setData({
          unit: unit
        })
      },
    })
  },
  // 获取文章数据
  getChapter() {
    let that = this
    app.request(app.apiDomain + 'index.php?c=health&a=recommend', {
      page: that.data.page,
      size: that.data.size,
      type: 1
    }, function (res) {
       let chapter = res.data.data
      if (res.data.status == 1) {
        if (res.data.data.length < that.data.size) {
          that.setData({
            chapter: that.data.chapter.concat(chapter)
          })
          if (that.data.page == 1) {

          } else {
            wx.showToast({
              title: '已经加载完了',
              duration: 2000,
              icon: 'none'
            })
          }
          return false
        } else if (res.data.data.length == that.data.size){
          that.setData({
            chapter: that.data.chapter.concat(chapter),
            isBottom: false
          })
        }
       } else {
         wx.showToast({
           title: res.data.info,
           duration: 2000,
           icon: 'none'
         })
         return false
       }
    }, 'POST')
  },
  backTop: function () {
    // 控制滚动
    let that = this
    that.setData({
      scrollTop: 0
    })
  },
  // 打开规则
  openGz () {
    let that = this
    console.log(111)
    that.setData({
      openGuize: true
    })
  },
  // 获取数据
  getBMI () {
    let that = this
    app.request(app.apiDomain + 'index.php?c=bmi&a=getBmi', {
      id: that.data.id,
      news: that.data.news
    },function (res) {
      if (res.data.status == 1) {
        let bmi = res.data.data.bmi
        let sex = res.data.data.sex
        let age = res.data.data.age
        let fat_rate = res.data.data.fat_rate
        let target = res.data.data.latest.target
        let total_num = res.data.data.total_num
        let renwu_url = '//resource.160nurse.com/canvas/healthy/img/bmi/female_bz.png'
        if (sex == 1) {
          if (bmi && parseFloat(bmi) < 18.5) {
            renwu_url = '//resource.160nurse.com/canvas/healthy/img/bmi/male_ps.png'
          } else if (bmi && parseFloat(bmi) < 24) {
            renwu_url = '//resource.160nurse.com/canvas/healthy/img/bmi/male_bz.png'
          } else if (bmi && parseFloat(bmi) < 28) {
            renwu_url = '//resource.160nurse.com/canvas/healthy/img/bmi/male_cz.png'
          } else if (bmi && parseFloat(bmi) >= 28) {
            renwu_url = '//resource.160nurse.com/canvas/healthy/img/bmi/male_fat.png'
          } else {
            renwu_url = '//resource.160nurse.com/canvas/healthy/img/bmi/inde_default_male.png'
            // test_font = '您的体'
          }
        } else {
          if (bmi && parseFloat(bmi) < 18.5) {
            renwu_url = '//resource.160nurse.com/canvas/healthy/img/bmi/female_ps.png'
          } else if (bmi && parseFloat(bmi) < 24) {
            renwu_url = '//resource.160nurse.com/canvas/healthy/img/bmi/female_bz.png'
          } else if (bmi && parseFloat(bmi) < 28) {
            renwu_url = '//resource.160nurse.com/canvas/healthy/img/bmi/female_cz.png'
          } else if (bmi && parseFloat(bmi) >= 28) {
            renwu_url = '//resource.160nurse.com/canvas/healthy/img/bmi/female_fat.png'
          } else {
            // default_url = '//resource.160nurse.com/canvas/healthy/img/new_index/index_female.png'
          }
        }
        
        // 体脂率
        let tizhi = that.calcTizhi(sex, age, fat_rate)
        let firstWeight = res.data.data.latest.length != 0 ? res.data.data.latest.weight : 0
        let cha = parseFloat(target) > parseFloat(res.data.data.weight) ? parseFloat(target - res.data.data.weight).toFixed(1) : parseFloat(res.data.data.weight - target).toFixed(1)
        console.log(typeof target, typeof res.data.data.weight, typeof cha)
        that.setData({
          bmi,
          fat_rate,
          height: res.data.data.height,
          weight: res.data.data.weight,
          sex,
          age,
          target,
          renwu_url,
          tizhi,
          total_num,
          firstWeight,
          weight_cha: cha
        })
        console.log(res.data.data.weight, res.data.data.height, target)
        if (res.data.data.latest.length != 0 && target != 0) {
          let step = (res.data.data.weight - res.data.data.latest.weight) / (target - res.data.data.latest.weight)
          that.drawProgress(step)
        }
      }
    }, 'POST')
  },
  onShow() {
    console.log('开始')
    this.getDailyData()
  },
  // 获取日历数据
  getDailyData() {
    let that = this
    app.request(app.apiDomain + 'index.php?c=bmi&a=listBmi', {
      month: that.data.currentDate,
    }, function (res){
      if (res.data.status == 1) {
        let length = res.data.data.list.length
        let list = res.data.data.list
        for (let i = 0; i < length; i ++) {
          let date = list[i].to_date.split('-')[2]
          let weight_cha = that.data.firstWeight < list[i].weight ? parseFloat(list[i].weight - that.data.firstWeight).toFixed(2) : parseFloat(that.data.firstWeight - list[i].weight).toFixed(2)
          list[i]['date'] = parseInt(date)
          list[i]['weight_cha'] = weight_cha
        }
        that.setData({
          list: list,
          record: res.data.data.record
        })
        setTimeout(() => {
          that.drawZuobiao()
        }, 1000)
        // console.log(list)
      }
    }, 'POST')
  },
  closePop () {
    this.setData({
      curDate: '',
      openGuize: false
    })
  },
  // 打开气泡
  openPop(e) {
    console.log(11)
    let that = this
    let str = e.target.dataset.str
    let flag = e.target.dataset.flag
    if (flag) {
      that.setData( {
        curDate: str
      })
      // setTimeout(function () {
        // that.setData({
        //   curDate: ''
        // })
      // }, 1500)
    } else {
      that.setData({
        curDate: ''
      })
    }
  },
  calcTizhi(sex, age, fat_rate) {
    let tizhi = ''
    if (sex == 1) {
      if (age == 0) {
        if (fat_rate >= 5 && fat_rate <= 10) {
          tizhi = 0
        } else if (fat_rate >= 11 && fat_rate <= 21) {
          tizhi = 1
        } else if (fat_rate >= 22 && fat_rate <= 26) {
          tizhi = 2
        } else if (fat_rate <= 0) {
          tizhi = 0
        } else {
          tizhi = 3
        }
      } else if (age == 1) {
        if (fat_rate >= 5 && fat_rate <= 11) {
          tizhi = 0
        } else if (fat_rate >= 12 && fat_rate <= 22) {
          tizhi = 1
        } else if (fat_rate >= 23 && fat_rate <= 27) {
          tizhi = 2
        } else if (fat_rate <= 0) {
          tizhi = 0
        } else {
          tizhi = 3
        }
      } else {
        if (fat_rate >= 5 && fat_rate <= 13) {
          tizhi = 0
        } else if (fat_rate >= 14 && fat_rate <= 24) {
          tizhi = 1
        } else if (fat_rate >= 25 && fat_rate <= 29) {
          tizhi = 2
        } else if (fat_rate <= 0) {
          tizhi = 0
        } else {
          tizhi = 3
        }
      }
    } else {
      if (age == 0) {
        if (fat_rate >= 5 && fat_rate <= 20) {
          tizhi = 0
        } else if (fat_rate >= 21 && fat_rate <= 34) {
          tizhi = 1
        } else if (fat_rate >= 35 && fat_rate <= 39) {
          tizhi = 2
        } else if (fat_rate <= 0) {
          tizhi = 0
        } else {
          tizhi = 3
        }
      } else if (age == 1) {
        if (fat_rate >= 5 && fat_rate <= 21) {
          tizhi = 0
        } else if (fat_rate >= 22 && fat_rate <= 35) {
          tizhi = 1
        } else if (fat_rate >= 36 && fat_rate <= 40) {
          tizhi = 2
        } else if (fat_rate <= 0) {
          tizhi = 0
        } else {
          tizhi = 3
        }
      } else {
        if (fat_rate >= 5 && fat_rate <= 22) {
          tizhi = 0
        } else if (fat_rate >= 23 && fat_rate <= 36) {
          tizhi = 1
        } else if (fat_rate >= 37 && fat_rate <= 41) {
          tizhi = 2
        } else if (fat_rate <= 0) {
          tizhi = 0
        } else {
          tizhi = 3
        }
      }
    }
    return tizhi
  },
  /**
   * 画进度条
   * */
  getWidth: function () {
    var that = this
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          unit: res.screenWidth / 100,
          sysWidth: res.screenWidth
        })
      }
    })
  },
  drawCanvasbg: function () {
    var that = this
    let unit = that.data.unit
    var ctx = wx.createCanvasContext('bg')
    ctx.setLineWidth(1.6 * unit)
    ctx.setStrokeStyle('#EEEEEE')
    ctx.setLineCap('round')
    ctx.beginPath();
    ctx.arc(21.33 * unit, 21.33 * unit, 20.53 * unit, 0.75 * Math.PI, 2.25 * Math.PI, false);
    ctx.stroke();
    ctx.draw();
  },
  drawProgress (step) {
    var that = this
    let unit = that.data.unit
    let width = that.data.sysWidth
    var ctx = wx.createCanvasContext('progress')
    ctx.setLineWidth(1.6 * unit)
    ctx.setStrokeStyle('#00D2C3')
    ctx.setLineCap('round')
    ctx.beginPath()
    if (step > 0) {
      // ctx.arc(20.53 * unit, 20.53 * unit, 19 * unit, 0.75 * Math.PI, 2.25 * Math.PI, false);
      ctx.arc(21.33 * unit, 21.33 * unit, 20.53 * unit, 0.75 * Math.PI, step * 1.5 * Math.PI + 0.75 * Math.PI, false)
    }
    ctx.stroke()
    ctx.draw()
  },
  /**
   * 日历滑动的特效处理函数
   */
  touchStart(e) {
    this.setData({
      startX: e.changedTouches[0].pageX
    })
  },
  touchEnd(e) {
    if (!this.data.slideFlag) {
      this.setData({
        slideFlag: true,
        endX: e.changedTouches[0].pageX
      })
      let disX = e.changedTouches[0].pageX - this.data.startX;
      if (disX < -150) {
        console.log("左滑")
        this.setData({
          slideOne: "animated fadeOutLeft",
          slideTwo: "animated fadeInRight"
        })
        setTimeout(() => {
          this.tapNext();
        }, 300);
        setTimeout(() => {
          this.setData({
            slideFlag: false,
            slideOne: "",
            slideTwo: ""
          })
        }, 800);
      } else if (disX > 150) {
        console.log("右滑")
        this.setData({
          slideOne: "animated fadeOutRight",
          slideTwo: "animated fadeInLeft"
        })
        setTimeout(() => {
          this.tapPrev();
        }, 300);
        setTimeout(() => {
          this.setData({
            slideFlag: false,
            slideOne: "",
            slideTwo: ""
          })
        }, 800);
      } else {
        this.setData({
          slideFlag: false
        })
      }
    }
  },
  /**
   * 左右点击
   */
  clickSlide (e) {
    if (!this.data.slideFlag) {
      this.setData({
        slideFlag: true,
        endX: e.changedTouches[0].pageX
      })
      let disX = e.changedTouches[0].pageX - this.data.startX;
      if (e.target.dataset.str == 'next') {
        console.log("左滑")
        this.setData({
          slideOne: "animated fadeOutLeft",
          slideTwo: "animated fadeInRight"
        })
        setTimeout(() => {
          this.tapNext();
        }, 300);
        setTimeout(() => {
          this.setData({
            slideFlag: false,
            slideOne: "",
            slideTwo: ""
          })
        }, 800);
      } else if (e.target.dataset.str == 'prev') {
        console.log("右滑")
        this.setData({
          slideOne: "animated fadeOutRight",
          slideTwo: "animated fadeInLeft"
        })
        setTimeout(() => {
          this.tapPrev();
        }, 300);
        setTimeout(() => {
          this.setData({
            slideFlag: false,
            slideOne: "",
            slideTwo: ""
          })
        }, 800);
      } else {
        this.setData({
          slideFlag: false
        })
      }
    }
  },
  /**
   * 左右滑动调用的函数
   */
  tapPrev() {
    let date = new Date(this.data.currentDate);
    date.setMonth(date.getMonth() - 1);
    this.setData({
      currentDate: utils.formatDate(date)
    })
    this.generateDaily()
    this.getDailyData()
  },
  tapNext() {
    let date = new Date(this.data.currentDate);
    date.setMonth(date.getMonth() + 1);
    this.setData({
      currentDate: utils.formatDate(date)
    })
    this.generateDaily()
    this.getDailyData()
  },
  generateDaily() {
    let date = new Date(this.data.currentDate)
    let year = date.getFullYear()
    let month = date.getMonth()
    let day = date.getDate()
    let isRunnian = this.calculatYear(year)
    let days = []
    if (isRunnian) {
      days = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    } else {
      days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    }
    // 计算月第一天是星期几,以及上个月的天数
    let fistDay = new Date(year + '/' + (month + 1) + '/01').getDay()
    let preDays = 0
    if (month == 0) {
      preDays = days[11]
    } else {
      preDays = days[month - 1]
    }
    //计算最后一天是星期几
    let lastDay = new Date(year + '/' + (month + 1) + '/' + days[month]).getDay()
    let lastDays = 0
    if (month == 11) {
      lastDays = days[0]
    } else {
      lastDays = days[month + 1]
    }
    console.log(lastDay, lastDays, fistDay, preDays)
    this.setData({
      days,
      month,
      preDays,
      fistDay,
      lastDay,
      lastDays,
      avgDay: parseInt(days[month]/2)
    })
  },
  // 计算闰年还是平年
  calculatYear(year) {
    if (year % 4 == 0 && year % 100 != 0) {
      return true
    } else {
      return false
    }
  },
  // 记录信息
  openRecord() {
    console.log(111)
    let that = this
    this.backTop()
    that.setData({
      recordMask: true,
      inputFocus2: true
    })
  },
  closeInvite(){
    let that = this
    that.setData({
      openInvite: false,
      openSave:false
    })
  },
  openInvite () {
    let that = this
    that.backTop()
    that.setData({
      openInvite: true
    })
  },
  // 获取图片信息
  getGoodsImgPath: function (url) {
    return new Promise((success, fail) => {
      wx.getImageInfo({
        src: url,
        success: res => {
          success(res.path);
        },
        fail: res => {
          fail(res);
        }
      })
    });
  },
  genePic() {
    let that = this
    that.setData({
      openSave:true
    })
    this.geneHb()
  },
  // 生成海报
  geneHb() {
    let that = this
    wx.showLoading({
      title: '正在准备海报',
      icon: 'none'
    })
    let ctx = wx.createCanvasContext('share_pic')
    let url = 'https:' + that.data.renwu_url
    let url_text = 'https://resource.160nurse.com/canvas/healthy/img/bmi/quanquan.png'
    let url_icon = 'https://resource.160nurse.com/canvas/healthy/img/bmi/weight.png'
    ctx.fillStyle='#fff'
    ctx.fillRect(0, 0, 85.33 * that.data.unit, 140 * that.data.unit)
    let back = 'https://resource.160nurse.com/canvas/healthy/img/bmi/white.png'
    that.getGoodsImgPath(url).then((res) => {
      ctx.save()
      ctx.drawImage(res, 4.26 * that.data.unit, 7.46 * that.data.unit, 33.86 * that.data.unit, 42.4 * that.data.unit)
      ctx.restore()
      that.getGoodsImgPath(url_text).then((res2) => {
        ctx.save()
        ctx.drawImage(res2, 41.6 * that.data.unit, 9.06 * that.data.unit, 39.46 * that.data.unit, 34.4 * that.data.unit)
        ctx.restore()
        ctx.setFontSize(3.2 * that.data.unit)
        ctx.fillStyle = '#999999'
        ctx.fillText('今日体重(kg)', 51.2 * that.data.unit, 18.73 * that.data.unit)
        ctx.setFontSize(11.73 * that.data.unit)
        ctx.fillStyle = '#333333'
        ctx.fillText(that.data.weight, 50.26 * that.data.unit, 32.26 * that.data.unit)
        ctx.setFontSize(3.2 * that.data.unit)
        ctx.fillStyle = '#999999'
        ctx.fillText('距离目标：', 47.2 * that.data.unit, 38.2 * that.data.unit)
        ctx.setFontSize(4.26 * that.data.unit)
        ctx.fillStyle = '#00D2C3'
        ctx.fillText(that.data.weight_cha, 62.2 * that.data.unit, 38.2 * that.data.unit)
        ctx.setFontSize(3.2 * that.data.unit)
        ctx.fillStyle = '#999999'
        ctx.fillText('(kg)', 69.2 * that.data.unit, 38.2 * that.data.unit)
        ctx.setFontSize(7.46 * that.data.unit)
        ctx.fillStyle = '#333333'
        ctx.fillText(that.data.total_num, 9.26 * that.data.unit, 62.26 * that.data.unit)
        ctx.setFontSize(3.2 * that.data.unit)
        ctx.fillStyle = '#999999'
        ctx.fillText('坚持记录(天)', 5.33 * that.data.unit, 66.93 * that.data.unit)
        ctx.setFontSize(7.46 * that.data.unit)
        ctx.fillStyle = '#333333'
        ctx.fillText(that.data.target, 35.06 * that.data.unit, 62.26 * that.data.unit)
        ctx.setFontSize(3.2 * that.data.unit)
        ctx.fillStyle = '#999999'
        ctx.fillText('目标体重(kg)', 32.53 * that.data.unit, 66.93 * that.data.unit)
        ctx.setFontSize(7.46 * that.data.unit)
        ctx.fillStyle = '#333333'
        ctx.fillText(that.data.bmi, 62.53 * that.data.unit, 62.26 * that.data.unit)
        ctx.setFontSize(3.2 * that.data.unit)
        ctx.fillStyle = '#999999'
        ctx.fillText('肥胖值(BMI)', 60.8 * that.data.unit, 66.93 * that.data.unit)
        ctx.strokeStyle = '#F4F4F4'
        // ctx.moveTo(4.26 * that.data.unit, 74.66 * that.data.unit)
        // ctx.lineTo(81.06 * that.data.unit, 74.66 * that.data.unit)
        ctx.stroke()
        that.getGoodsImgPath(url_icon).then((res3) => {
          ctx.save()
          ctx.drawImage(res3, 4.26 * that.data.unit, 79.2 * that.data.unit, 3.46 * that.data.unit, 3.46 * that.data.unit)
          ctx.restore()
          ctx.setFontSize(3.46 * that.data.unit)
          ctx.fillStyle = '#333'
          ctx.fillText('体重变化', 8.8 * that.data.unit, 82.2 * that.data.unit)
          that.drawZuobiao2(ctx)
          // ctx.draw()
          wx.hideLoading()
        })
      })
    })
    // ctx.drawImage(url_text, 5.86 * that.data.unit, 37.26 * that.data.unit, 46.66 * that.data.unit, 8.53 * that.data.unit)
  },
  // 设定目标
  setGold () {
    this.setData({
      openSetGold: true,
      inputFocus: true
    })
  },
  closeMask() {
    this.setData({
      openSetGold: false,
      recordMask: false,
      inputFocus: false,
      inputFocus2:false
    })
  },
  inputChange (e) {
    let currentValue = e.detail
    this.setData({
      currentValue
    })
    console.log(currentValue)
  },
  stepChange (e) {
    let currentWeight = e.detail
    this.setData({
      currentWeight
    })
  },
  submitToday () {
    let that = this
    if (this.data.currentWeight.length < 3) {
      return false
    }
    let weight = parseFloat(that.data.currentWeight / 10)
    let height = parseFloat(that.data.height).toFixed(2)
    let age = that.data.age
    let sex = that.data.sex
    let BMI = parseFloat(parseFloat(weight) / (height * height)).toFixed(1)
    let fatRate = 0
    if (sex == 1) {
      fatRate = parseFloat(1.2 * BMI + 0.23 * age - 5.4 - 10.8).toFixed(1)
    } else {
      fatRate = parseFloat(1.2 * BMI + 0.23 * age - 5.4).toFixed(1)
    }
    app.request(app.apiDomain + 'index.php?c=bmi&a=setBmi', {
      weight: weight,
      height: height,
      age: age,
      sex: sex,
      bmi: BMI,
      fat_rate: fatRate,
      type: 1
    }, function (res){
      if (res.data.status == 1) {
        let date = parseInt(new Date().getDate())
        let age = res.data.data.age
        let height = res.data.data.height
        let fat_rate = res.data.data.fat_rate
        let point = parseInt(res.data.data.point)
        let weight = res.data.data.weight
        let total_num = res.data.data.total_num
        let bmi = BMI
        that.data.list[date - 1].display = 1
        that.data.list[date - 1].bmi = BMI
        that.data.list[date - 1].weight = weight
        let weight_cha = weight > that.data.target ? parseFloat(weight - that.data.target).toFixed(1) : parseFloat(that.data.target -weight).toFixed(1)
        console.log(bmi, fat_rate)
        that.setData({
          age,
          weight,
          height,
          record: parseInt(that.data.record) + point,
          total_num,
          fat_rate,
          list: that.data.list,
          bmi,
          weight_cha: weight_cha,
          bottom: 0,
          recordMask: false
        })
        let step = (weight - that.data.firstWeight) / (that.data.target - that.data.firstWeight)
        console.log(weight, that.data.firstWeight, that.data.target)
        that.drawProgress(step)
        that.drawZuobiao()
        wx.showToast({
          title: res.data.info,
          duration: 1000
        })
      } else {
        wx.showToast({
          title: res.data.info,
          duration: 1000,
          icon: 'none'
        })
        that.setData({
          recordMask: false
        })
      }
    }, 'POST')
  },
  submit () {
    let that = this
    if (this.data.currentValue.length < 3) {
      return false
    }
    let weight = parseFloat(that.data.currentValue / 10)
    app.request(app.apiDomain + 'index.php?c=bmi&a=target', {
      weight: weight
    }, function (res) {
      if (res.data.status == 1) {
        that.getBMI()
      }
      that.setData({
        openSetGold: false,
        currentValue: ''
      })
    }, 'POST')
  },
  // 修改个人信息
  linkTo() {
    wx.redirectTo({
      url: './index?type=' + this.data.type + '&id=' + this.data.id + '&sex=' + this.data.sex,
    })
  },
  goPlay () {
    let that = this
    if (that.data.isIphone) {
      if (that.data.isIphoneX) {
        wx.navigateTo({
          url: '../playIos/index_ix',
        })
      } else {
        wx.navigateTo({
          url: '../playIos/index',
        })
      }
    } else {
      wx.navigateTo({
        url: '../play/index',
      })
    }
  },
  onReady() {
    app.SystemInfo(this)
  },
  drawZuobiao2(ctx) {
    let that = this
    let data = that.data.list
    // console.log(data)
    let maxWeight = 0;
    let minWeight = 0;
    for (let i = 0; i < that.data.list.length; i++) {
      if (that.data.list[i].hasOwnProperty('weight')) {
        maxWeight = that.data.list[i].weight
        minWeight = that.data.list[i].weight
        break;
      }
    }
    let price = (that.data.unit * 76.8) / (that.data.list.length + 1)
    for (let item of that.data.list) {
      if (item.hasOwnProperty('weight') && item.weight < minWeight) {
        minWeight = item.weight
      }
      if (item.hasOwnProperty('weight') && item.weight > maxWeight) {
        maxWeight = item.weight
      }
    }
    let allMargin = maxWeight - minWeight + 10
    ctx.lineWidth = 1.5;//线条的宽度
    ctx.strokeStyle = "#00D2C3";//线条的颜色
    let number = 0
    for (let i = 0; i < that.data.list.length; i++) {
      if (that.data.list[i].hasOwnProperty('weight')) {
        let y = (data[i].weight - minWeight + 5) / allMargin
        // console.log(y)
        ctx.lineTo(price * i + 76.8 * that.data.unit / (that.data.list.length + 1), (1 - y) * (that.data.unit * 20) + 84.26 * that.data.unit)
        number = i
      }
    }
    ctx.stroke()
    let grd = null
    let index = 0
    for (let i = 0; i < that.data.list.length; i++) {
      if (that.data.list[i].hasOwnProperty('weight')) {
        grd = ctx.createLinearGradient(76.8 * that.data.unit / (that.data.list.length + 1), (1 - (that.data.list[i].weight - minWeight + 5) / allMargin) * (that.data.unit * 20), 76.8 * that.data.unit / (that.data.list.length + 1), (that.data.unit * 20) + 84.26 * that.data.unit)
        index = i
        break;
      }
    }
    if (grd != null) {
      grd.addColorStop(0, 'rgba(0,210,195,.8)')
      grd.addColorStop(0.1, 'rgba(0,210,195,.45)')
      grd.addColorStop(0.2, 'rgba(0,210,195,.4)')
      grd.addColorStop(0.3, 'rgba(0,210,195,.35)')
      grd.addColorStop(0.4, 'rgba(0,210,195,.3)')
      grd.addColorStop(0.5, 'rgba(0,210,195,.25)')
      grd.addColorStop(0.6, 'rgba(0,210,195,.2)')
      grd.addColorStop(0.7, 'rgba(0,210,195,.15)')
      grd.addColorStop(0.8, 'rgba(0,210,195,.1)')
      grd.addColorStop(1, 'rgba(0,210,195,.05)')
      ctx.fillStyle = grd;
    }
    // ctx.strokeStyle = "#f00";
    ctx.lineWidth = 0.05;
    ctx.lineTo(price * number + 76.8 * that.data.unit / (that.data.list.length + 1), (that.data.unit * 20) + 84.26 * that.data.unit)
    ctx.lineTo(price * index + 76.8 * that.data.unit / (that.data.list.length + 1), (that.data.unit * 20) + 84.26 * that.data.unit)
    ctx.lineTo(price * index + 76.8 * that.data.unit / (that.data.list.length + 1), (1 - (that.data.list[index].weight - minWeight + 5) / allMargin) * (that.data.unit * 20) + 84.26 * that.data.unit)
    ctx.stroke()
    ctx.fill()
    for (let i = 0; i < data.length; i++) {
      if (that.data.list[i].hasOwnProperty('weight')) {
        let y = (data[i].weight - minWeight + 5) / allMargin
        // console.log(y)
        ctx.fillStyle = '#00D2C3'
        ctx.beginPath()
        ctx.arc(price * i + 76.8 * that.data.unit / (that.data.list.length + 1), (1 - y) * (that.data.unit * 20) + 84.26 * that.data.unit, 2, 0, Math.PI * 2, true)
        ctx.closePath()
        ctx.fill()
        ctx.stroke()
      }
    }
    ctx.strokeStyle = '#eee'
    // ctx.lineWidth = '1'
    ctx.moveTo(4.26 * that.data.unit, 20 * that.data.unit + 84.26 * that.data.unit)
    ctx.lineTo(76.8 * that.data.unit, 20 * that.data.unit + 84.26 * that.data.unit)
    ctx.moveTo(4.26 * that.data.unit, 10 * that.data.unit + 84.26 * that.data.unit)
    ctx.lineTo(76.8 * that.data.unit, 10 * that.data.unit + 84.26 * that.data.unit)
    // ctx.moveTo(4.26 * that.data.unit, 0 * that.data.unit + 84.26 * that.data.unit)
    // ctx.lineTo(76.8 * that.data.unit, 0 * that.data.unit + 84.26 * that.data.unit)
    ctx.stroke()
    ctx.setFontSize(2.66 * that.data.unit)
    ctx.fillStyle = '#999'
    ctx.fillText((that.data.month + 1) + '/1', 4.26 * that.data.unit, 108.2 * that.data.unit)
    ctx.stroke()
    ctx.setFontSize(2.66 * that.data.unit)
    ctx.fillStyle = '#999'
    ctx.fillText((that.data.month + 1) + '/' + (that.data.avgDay - 7), 18.26 * that.data.unit, 108.2 * that.data.unit)
    ctx.stroke()
    ctx.setFontSize(2.66 * that.data.unit)
    ctx.fillStyle = '#999'
    ctx.fillText((that.data.month + 1) + '/' + that.data.avgDay, 35.6 * that.data.unit, 108.2 * that.data.unit)
    ctx.stroke()
    ctx.setFontSize(2.66 * that.data.unit)
    ctx.fillStyle = '#999'
    ctx.fillText((that.data.month + 1) + '/' + (that.data.avgDay + 8), 54 * that.data.unit, 108.2 * that.data.unit)
    ctx.setFontSize(2.66 * that.data.unit)
    ctx.fillStyle = '#999'
    ctx.fillText((that.data.month + 1) + '/' + (that.data.days[that.data.month]), 72.93 * that.data.unit, 108.2 * that.data.unit)
    let urls = 'https://resource.160nurse.com/canvas/healthy/img/bmi/160.png'
    let urls_code = 'https://resource.160nurse.com/canvas/healthy/img/bmi/code.png'
    let weight_url = ''
    if (that.data.bmi < 18.5) {
      weight_url = 'https://resource.160nurse.com/canvas/healthy/img/bmi/ps.png'
    } else if (that.data.bmi < 24) {
      weight_url = 'https://resource.160nurse.com/canvas/healthy/img/bmi/bz.png'
    } else if (that.data.bmi < 28) {
      weight_url = 'https://resource.160nurse.com/canvas/healthy/img/bmi/cz.png'
    } else {
      weight_url = 'https://resource.160nurse.com/canvas/healthy/img/bmi/fat.png'
    }
    that.getGoodsImgPath(urls).then((res) => {
      ctx.save()
      ctx.drawImage(res, 4.26 * that.data.unit, 122.06 * that.data.unit, 43.46 * that.data.unit, 11.46 * that.data.unit)
      ctx.restore()
      that.getGoodsImgPath(urls_code).then((res2) => {
        ctx.save()
        ctx.drawImage(res2, 63.46 * that.data.unit, 114.6 * that.data.unit, 16.8 * that.data.unit, 16.8 * that.data.unit)
        ctx.restore()
        ctx.setFontSize(2.66 * that.data.unit)
        ctx.strokeStyle = '#666666'
        ctx.fillText('长按识别小程序码立即体验！', 50.4 * that.data.unit, 136.26 * that.data.unit)
        ctx.strokeStyle = '#000'
        ctx.moveTo(4.26 * that.data.unit, 74.66 * that.data.unit)
        ctx.lineTo(81.06 * that.data.unit, 74.66 * that.data.unit)
        ctx.stroke()
        that.getGoodsImgPath(weight_url).then((res3) => {
          ctx.save()
          ctx.drawImage(res3, 65.86 * that.data.unit, 50.13 * that.data.unit, 8.53 * that.data.unit, 4.26 * that.data.unit)
          ctx.restore()
          ctx.draw(false, function () {
            console.log('draw()是否完成')
          })
        })
      })
    })
  },
  saveImg() {
    let that = this
    if (that.data.isClick) {
      return false
    }
    wx.showToast({
      title: '保存中...',
      icon: 'none'
    })
    let shareImg = ''
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      width: 85.33 * that.data.unit,
      height: 140 * that.data.unit,
      destWidth: 85.33 * that.data.unit * 2,
      destHeight: 140 * that.data.unit * 2,
      canvasId: 'share_pic',
      quality: 1,
      success(res) {
        shareImg = res.tempFilePath
        wx.getSetting({
          success: function (res) {
            that.setData({
              isClick: true
            })
            wx.authorize({
              scope: 'scope.writePhotosAlbum',
              success: function (resp) {
                // let imgUrl = shareImg
                // console.log(imgUrl)
                // wx.downloadFile({
                //   url: imgUrl,
                //   success: function (res) {
                //     wx.hideLoading()
                //     // console.log(respon);
                wx.saveImageToPhotosAlbum({
                  filePath: shareImg,
                  success: function (response) {
                    console.log(response)
                    that.setData({
                      isClick: false,
                      openInvite: false
                    })
                    wx.hideLoading()
                    wx.showToast({
                      title: '保存成功',
                      icon: 'success'
                    })
                  }
                })
                //   }
                // })
              },
              fail: function () {
                wx.hideLoading()
                that.setData({
                  isClick: false
                })

              },
              complete: function (res) {
                // wx.hideLoading()
                console.log(res)
                if (res.errMsg.indexOf('authorize:fail') !== -1) {
                  wx.showToast({
                    title: '您未打开授权，请前往个人中心授权管理开启授权',
                    icon: 'none'
                  })
                }
                that.setData({
                  isClick: false
                })
              }
            })
          }
        })
      }
    })
  },
  //画曲线
  drawZuobiao() {
    let that = this
    let ctx = wx.createCanvasContext('weight', this)
    let data = that.data.list
    // console.log(data)
    let maxWeight = 0;
    let minWeight = 0;
    for (let i = 0; i < that.data.list.length; i++) {
      if (that.data.list[i].hasOwnProperty('weight')) {
        maxWeight = that.data.list[i].weight
        minWeight = that.data.list[i].weight
        break;
      }
    }
    let price = (that.data.unit * 88) / (that.data.list.length+1)
    for (let item of that.data.list) {
      if (item.hasOwnProperty('weight') && item.weight < minWeight) {
        minWeight = parseFloat(item.weight).toFixed(1) * 1
      }
      if (item.hasOwnProperty('weight') && item.weight > maxWeight) {
        maxWeight = parseFloat(item.weight).toFixed(1) * 1
      }
    }
    let allMargin = maxWeight - minWeight + 10
    ctx.lineWidth = 1.5;//线条的宽度
    ctx.strokeStyle = "#00D2C3";//线条的颜色
    let number = 0
    for (let i = 0; i < that.data.list.length; i++) {
      if (that.data.list[i].hasOwnProperty('weight')) {
        let y = (data[i].weight - minWeight + 5) / allMargin
        // console.log(y)
        ctx.lineTo(price * i + 88 * that.data.unit / (that.data.list.length+1) , (1 - y) * (that.data.unit * 28.8))
        number = i
      }
    }
    ctx.stroke()
    let grd = null
    let index = 0
    for (let i = 0; i < that.data.list.length; i++) {
      if (that.data.list[i].hasOwnProperty('weight')) {
        grd = ctx.createLinearGradient(88 * that.data.unit / (that.data.list.length + 1), (1 - (that.data.list[i].weight - minWeight + 5) / allMargin) * (that.data.unit * 28.8), 88 * that.data.unit / (that.data.list.length + 1) , (that.data.unit * 28.8))
        index = i
        break;
      }
    }
    if (grd != null) {
      grd.addColorStop(0, 'rgba(0,210,195,.5)')
      grd.addColorStop(0.1, 'rgba(0,210,195,.45)')
      grd.addColorStop(0.2, 'rgba(0,210,195,.4)')
      grd.addColorStop(0.3, 'rgba(0,210,195,.35)')
      grd.addColorStop(0.4, 'rgba(0,210,195,.3)')
      grd.addColorStop(0.5, 'rgba(0,210,195,.25)')
      grd.addColorStop(0.6, 'rgba(0,210,195,.2)')
      grd.addColorStop(0.7, 'rgba(0,210,195,.15)')
      grd.addColorStop(0.8, 'rgba(0,210,195,.1)')
      grd.addColorStop(1, 'rgba(0,210,195,.05)')
      ctx.fillStyle = grd;
    }
    // ctx.strokeStyle = "#f00";
    ctx.lineWidth = 0.05;
    ctx.lineTo(price * number + 88 * that.data.unit / (that.data.list.length + 1) , (that.data.unit * 28.8))
    ctx.lineTo(price * index + 88 * that.data.unit / (that.data.list.length + 1) , (that.data.unit * 28.8))
    ctx.lineTo(price * index + 88 * that.data.unit / (that.data.list.length + 1) , (1 - (that.data.list[index].weight - minWeight + 5) / allMargin) * (that.data.unit * 28.8))
    ctx.stroke()
    ctx.fill()
    for (let i = 0; i < data.length; i++) {
      if (that.data.list[i].hasOwnProperty('weight')) {
        let y = (data[i].weight - minWeight + 5) / allMargin
        // console.log(y)
        ctx.fillStyle = '#00D2C3'
        ctx.beginPath()
        ctx.arc(price * i + 88 * that.data.unit / (that.data.list.length + 1) , (1 - y) * (that.data.unit * 28.8), 2, 0, Math.PI * 2, true)
        ctx.closePath()
        ctx.fill()
        ctx.stroke()
      }
    }
    ctx.strokeStyle = '#000'
    // ctx.lineWidth = '1'
    ctx.moveTo(0, 28.8 * that.data.unit)
    ctx.lineTo(88 * that.data.unit, 28.8 * that.data.unit)
    ctx.moveTo(0, 14.4 * that.data.unit)
    ctx.lineTo(88 * that.data.unit, 14.4 * that.data.unit)
    ctx.moveTo(0, 0 * that.data.unit)
    ctx.lineTo(88 * that.data.unit, 0 * that.data.unit)
    ctx.stroke()
    ctx.draw(false, function () {
      console.log('draw()是否完成')
    })
    that.setData({
      maxWeight: parseFloat((maxWeight + 5)).toFixed(1) * 1,
      minWeight: parseFloat((minWeight - 5)).toFixed(1) * 1,
      avgWeight: (parseFloat(maxWeight).toFixed(1) * 1 + parseFloat(minWeight).toFixed(1) * 1) / 2
    })
    console.log('最小值', that.data.maxWeight, that.data.minWeight)
  },
  // 下拉加载
  slideBottom () {
    let that = this
    if (that.data.isBottom) {
      return false
    }
    that.data.isBottom = true
    that.data.page++
    that.getChapter()
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let that = this
    var nickName = '';
    var userId = 0;
    try {
      nickName = wx.getStorageSync('nickname');
      userId = wx.getStorageSync('user_id');
    } catch (e) { }
    return {
      title: '每日称重，打卡领奖，有趣的减肥增重小助手',
      path: '/pages/index/index?user_id=' + userId,
      imageUrl: app.resourceDomain + 'canvas/healthy/img/bmi/share.png'
    }
  }
})